package com.controller;

import com.alibaba.fastjson.JSON;
import com.entity.User;
import com.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();

            // if
            {
                Map<String, String> param = new HashMap<String, String>();
                param.put("name", "哪吒");
                User user = sqlSession.selectOne("mapper.UserMapper.ifDemo", param);
                System.out.println(JSON.toJSONString(user));
            }

//            // choose
//            {
//                Map<String, Integer> param = new HashMap<String, Integer>();
//                param.put("index", 3);
//                User user = sqlSession.selectOne("mapper.UserMapper.chooseDemo", param);
//                System.out.println(JSON.toJSONString(user));
//            }

//            // foreach
//            {
//                List<User> listUser = new ArrayList<User>();
//                for (int i = 0; i < 5; i++) {
//                    User user = new User();
//                    user.setCode("2023003");
//                    user.setName("周杰伦" + i);
//                    listUser.add(user);
//                }
//
//                Map<String, List<User>> param = new HashMap<String, List<User>>();
//                param.put("listUser", listUser);
//                sqlSession.insert("mapper.UserMapper.foreachDemo", param);
//                System.out.println("foreache-inset-成功");
//
//                sqlSession.commit();
//            }

            // 释放资源
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
